package com.handpay.zztong.hp.klf;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;

import com.handpay.framework.ClientEngine;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.SwiperCardKLFActivity.BackListener;
import com.handpay.zztong.hp.log.HPLog;

// 自定义的SurfaceView子类  
public class SwiperCardView_KLF extends SurfaceView implements Callback {

    // 背景图
    private Bitmap cardImage;
    private Bitmap titleImage;
    private Bitmap vposImage;
    private Bitmap phoneImage;
    private Bitmap backImage;

    private int topPosition = 0;
    private int spacePostion = 0;
    private int top = 0;
    private boolean isSwiperOn = false;
    private boolean isBack = false;
    SurfaceHolder surfaceHolder;
    float rotate = 0;
    private int state = -1;
    private MyThread thread = null;
    private int praitTime = 200;
    public static int frameCount = 0;
    private float backLeftMin, backLeftMax, backHeightMax, backHeightMin;
    private Context context;
    private int screenWidth;
    private int screenHeight;
    private BackListener backListener;

    public SwiperCardView_KLF(Context context, AttributeSet set) {
        super(context, set);
        this.context = context;
        screenWidth = this.getResources().getDisplayMetrics().widthPixels;
        screenHeight = this.getResources().getDisplayMetrics().heightPixels;
        surfaceHolder = this.getHolder();// 获取holder
        surfaceHolder.setFormat(PixelFormat.TRANSPARENT);
        surfaceHolder.addCallback(this);
        setFocusable(true);
        setZOrderOnTop(true);
        frameCount = 0;
        String success = (String) ClientEngine.getInstance().getGlobal(
                "onOpenAndEnableSuccess");
        isSwiperOn = success != null && success.equals("1");
    }

    @Override
    public void setVisibility(int visibility) {
        HPLog.e("TAG", "SwiperCardView" + visibility);
        boolean isOn = true;
        state = visibility;

        if (visibility == 1) {
            isOn = true;
        } else if (visibility == 8) {
            isOn = false;
        } else {
            return;
        }

        if (isOn == isSwiperOn)
            return; // 如果是相同状态回避掉
        isSwiperOn = isOn;
        rotate = 0;

        if (isSwiperOn) {
            titleImage = BitmapFactory.decodeResource(getResources(),
                    R.drawable.skz);
        } else
            titleImage = BitmapFactory.decodeResource(getResources(),
                    R.drawable.crvpos);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (backLeftMin < event.getX() && event.getX() < backLeftMax
                    && backHeightMin < event.getY()
                    && event.getY() < backHeightMax) {
                // ScriptEngine.getInstance().execute("goLastPage", new
                // Object[]{});
                HPLog.i("Test", "返回按钮-----");
                if (backListener != null) {
                    backListener.back();
                }
            }
        }

        return true;
    }

    private void init() {
        cardImage = BitmapFactory.decodeResource(getResources(), R.drawable.sk);
        if (isSwiperOn) {
            titleImage = BitmapFactory.decodeResource(getResources(),
                    R.drawable.skz);
        } else
            titleImage = BitmapFactory.decodeResource(getResources(),
                    R.drawable.crvpos);
        vposImage = BitmapFactory.decodeResource(getResources(),
                R.drawable.vpos);
        phoneImage = BitmapFactory.decodeResource(getResources(),
                R.drawable.iphone);
        backImage = BitmapFactory.decodeResource(getResources(),
                R.drawable.erro);
        // backHeightMin = backLeftMin =
        // 20*getResources().getDisplayMetrics().density;
        // backHeightMax = backHeightMin+backImage.getHeight();
        // backLeftMax = backLeftMin+backImage.getWidth();

        backLeftMin = screenWidth - backImage.getWidth() - 20
                * getResources().getDisplayMetrics().density;
        backHeightMax = backHeightMin + backImage.getHeight();
        backLeftMax = screenWidth - 20
                * getResources().getDisplayMetrics().density;

        top = (int) (backImage.getHeight() + 46 * getResources()
                .getDisplayMetrics().density);
        spacePostion = getResources().getDimensionPixelSize(R.dimen.move_speed);
        topPosition = (screenHeight - titleImage.getHeight()
                - phoneImage.getHeight() - cardImage.getHeight() - spacePostion) / 2;
        if (top > topPosition)
            top = topPosition;
        else
            topPosition = top;
    }

    public void doDestroy() {
        thread.isDo = false;
        thread.interrupt();
    }

    // 自定义线程类
    class MyThread extends Thread {
        public boolean isDo = true;

        @Override
        public void run() {
            init();

            while (isDo && !this.isInterrupted()) {
                updateUI();
            }

        }
    }

    // Caojun
    private void paint(Canvas canvas) {
        try {
            synchronized (surfaceHolder) {

                // ----------------首次进入停止几秒再进行动画-----------------------
                // if (frameCount == 1) {
                // if(ClientEngine.getInstance()!=null &&
                // !ClientEngine.getInstance().slidingDrawer.isOpened())
                // Thread.sleep(400);
                // else
                // Thread.sleep(100);
                // }
                if (surfaceHolder == null)
                    return;
                if (canvas == null || cardImage == null
                        || cardImage.isRecycled() || titleImage == null
                        || titleImage.isRecycled() || vposImage == null
                        || vposImage.isRecycled() || phoneImage == null
                        || phoneImage.isRecycled() || backImage == null
                        || backImage.isRecycled())
                    return;

                canvas.drawColor(Color.TRANSPARENT, Mode.CLEAR);
                Paint mPaint = new Paint();
                mPaint.setAntiAlias(true);
                mPaint.setDither(true);
                // 绘制背景
                // if (frameCount < praitTime) {
                // canvas.drawBitmap(BackgroundImage, 0, 0, mPaint);
                // } else {
                // canvas.clipRect(new Rect(0, topPosition,
                // MainMenu.screenWidth, topPosition
                // + titleImage.getHeight() + spacePostion
                // + cardImage.getHeight()));
                // canvas.drawBitmap(BackgroundImage, 0, 0, mPaint);
                // }
                // mPaint.setColor(Color.WHITE);
                // 清屏
                // canvas.drawRect(0, 0, 720, 480, mPaint);
                // 创建矩阵以控制图片旋转和平移
                Matrix m = new Matrix();
                if (isBack) {

                    float displacement = (rotate) / 5;
                    if (displacement <= 1) {
                        rotate = rotate - 1;
                    } else {
                        rotate = rotate - displacement;
                    }
                    if (rotate <= 0) {
                        rotate = 0;
                        isBack = false;
                    }
                }

                int maxPosition = topPosition + titleImage.getHeight()
                        + spacePostion + cardImage.getHeight()
                        - (int) (vposImage.getHeight() * 0.67);
                if (isSwiperOn) {
                    if (!isBack) {
                        rotate += 2.5 * getResources().getDisplayMetrics().density;
                    }
                    m.postTranslate(rotate,
                            topPosition + titleImage.getHeight() + spacePostion
                                    / 2);
                    if (cardImage == null || cardImage.isRecycled()
                            || vposImage == null || vposImage.isRecycled())
                        return;
                    canvas.drawBitmap(cardImage, m, mPaint);
                    float position = topPosition + titleImage.getHeight()
                            + spacePostion + cardImage.getHeight()
                            - (int) (vposImage.getHeight() * 0.67);
                    canvas.drawBitmap(vposImage,
                            (screenWidth - vposImage.getWidth()) / 2, position,
                            mPaint);
                    // 休眠以控制最大帧频为每秒约30帧
                    if (rotate > screenWidth * 0.8) {
                        Thread.sleep(200);
                        isBack = true;
                    }
                } else {
                    if (!isBack) {
                        rotate += 0.8 * getResources().getDisplayMetrics().density;
                    }
                    float nextPosition = rotate + topPosition
                            + titleImage.getHeight() + spacePostion;

                    m.postTranslate((screenWidth - vposImage.getWidth()) / 2,
                            nextPosition);

                    canvas.drawBitmap(vposImage, m, mPaint);
                    if (nextPosition > maxPosition) {
                        if (state == 2) {
                            rotate -= 0.8 * getResources().getDisplayMetrics().density;
                        } else {
                            Thread.sleep(200);
                            isBack = true;
                        }
                    }
                }

                canvas.drawBitmap(titleImage,
                        (screenWidth - titleImage.getWidth()) / 2, top, mPaint);
                if (frameCount < praitTime) {
                    if (phoneImage == null || phoneImage.isRecycled())
                        return;
                    canvas.drawBitmap(phoneImage,
                            (screenWidth - phoneImage.getWidth()) / 2,
                            topPosition + titleImage.getHeight() + spacePostion
                                    + cardImage.getHeight(), mPaint);
                    canvas.drawBitmap(
                            backImage,
                            screenWidth
                                    - backImage.getWidth()
                                    - 20
                                    * getResources().getDisplayMetrics().density,
                            20 * getResources().getDisplayMetrics().density,
                            mPaint);
                }
                float textSize = getContext().getResources().getDimension(
                        R.dimen.twenty_sp);
                mPaint.setTextSize(textSize);
                mPaint.setColor(getContext().getResources().getColor(
                        R.color.keyboardnumber));
                String icText = getContext().getText(
                        R.string.please_ic_swiper_1).toString();
                Rect bounds = new Rect();
                mPaint.getTextBounds(icText, 0, icText.length(), bounds);
                float topText = (float) (topPosition + titleImage.getHeight()
                        + spacePostion + cardImage.getHeight()
                        + vposImage.getHeight() + spacePostion);
                canvas.drawText(icText, (screenWidth - bounds.width()) / 2,
                        topText, mPaint);
                topText = topText + (bounds.bottom + bounds.height());
                icText = getContext().getText(R.string.please_ic_swiper_2)
                        .toString();
                bounds = new Rect();
                mPaint.getTextBounds(icText, 0, icText.length(), bounds);
                canvas.drawText(icText, (screenWidth - bounds.width()) / 2,
                        topText, mPaint);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void updateUI() {
        // isPainted = false;
        frameCount++;
        Canvas canvas = null;
        try {
            if (frameCount < praitTime) {
                canvas = surfaceHolder.lockCanvas(null);// 获取画布
            } else {
                canvas = surfaceHolder.lockCanvas(new Rect(0, topPosition,
                        screenWidth, topPosition + titleImage.getHeight() + 3
                        + spacePostion + cardImage.getHeight()));
            }
            if (canvas != null) {
                synchronized (surfaceHolder) {
                    paint(canvas);
                }
            } else {
                // 避免多次进入导致黑屏的问题。具体原因请看SurfaceView源码 BUG 6890
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (canvas != null)
                    surfaceHolder.unlockCanvasAndPost(canvas);// 解锁画布，提交画好的图像
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {
        HPLog.i("Test", "surfaceChanged--------------");
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        thread = new MyThread();
        thread.start();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        doDestroy();
    }

    public void update() {
        init();
    }

    public void setIsSwiperOn(boolean isSwiperOn) {
        this.isSwiperOn = isSwiperOn;
    }

    public void setBackListener(BackListener backListener) {
        this.backListener = backListener;
    }

}
